package com.web.ShoppingDemo.daoImpl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;

import com.web.ShoppingDemo.dao.BaseDao;
@SuppressWarnings("unchecked")
@Repository("baseDao")
@Lazy(true)
public class BaseDaoImpl<T> implements BaseDao<T> {
	private Class<?> clazz;
	
	@Resource
	private SessionFactory sessionFactory;
	
	public BaseDaoImpl(){
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz=(Class<?>)type.getActualTypeArguments()[0];
	}
	
	protected Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	//保存
	@Override
	public void save(T t) {
		try{
			getSession().save(t);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	//更新
	@Override
	public void update(T t) {
		try {
			getSession().update(t);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//删除
	@Override
	public void delete(int id) {
		String hql = "DELETE "+clazz.getSimpleName()+" WHERE id=:id";
		getSession().createQuery(hql)
					.setInteger("id", id)
					.executeUpdate();
	}
	//得到一个对象
	@Override
	public T get(int id) {
		return (T)getSession().get(clazz, id);
	}
	//得到一组对象
	@Override
	public List<T> query() {
		String hql = "FROM "+clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}

}
